﻿using System;
using System.Net;
using System.Windows;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Xml;
using Windows.Storage;
using System.Threading.Tasks;
using System.Linq;
using Windows.Storage.Streams;
using System.IO;

namespace BlueRoseGames.Controls.Text
{
    public class Font
    {
        public Dictionary<int, Glyph> Glyphs
        {
            get;
            set;
        }

        public double Height
        {
            get;
            set;
        }

        public double PointSize
        {
            get;
            set;
        }

        public double Baseline
        {
            get;
            set;
        }

        public async Task Initialize(string fontUri)
        {
            string[] s = fontUri.Split('/');
            StorageFolder f = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFile file = null;
            for (int i = 0; i < s.Length - 1; i++)
            {
                f = await f.GetFolderAsync(s[i]);
            }
            try
            {
                file = await f.GetFileAsync(s.Last());
            }
            catch
            {
            }
            IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
            XDocument doc = XDocument.Load(readStream.GetInputStreamAt(0).AsStreamForRead());
            Glyphs = new Dictionary<int, Glyph>();
            Height = double.Parse(doc.Root.Attribute("height").Value);
            PointSize = double.Parse(doc.Root.Attribute("pointSize").Value);
            Baseline = double.Parse(doc.Root.Attribute("baseline").Value);
            foreach (XElement ele in doc.Root.Elements())
            {
                Glyph g = new Glyph(ele);
                Glyphs.Add(g.Key, g);
            }
        }
    }
}
